## -*- coding: utf-8 -*-

#   Copyright (C) 2007, 2008 Yves Junqueira (yves@cetico.org) 
#
#    This file is part of GeekDNS.
#
#    GeekDNS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    GeekDNS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with GeekDNS.  If not, see <http://www.gnu.org/licenses/>.

from turbogears import widgets, validators, identity,url
from model import *
from tgfastdata.datawidgets import FastDataGrid
from geekroot.register_widgets import NewUserSchema

distro_codes = []
distro_options = []
for distro in Distro.select():
  distro_codes.append(str(distro.id))
  distro_options.append((distro.id, distro.name))

panel_codes = []
panel_options = []
for panel in Panel.select():
  panel_codes.append(str(panel.id))
  panel_options.append((panel.id, panel.name))
  
planos_fields = [
  ('Plano', lambda row: row[0]),
  (u'Memória RAM em Mb', lambda row: row[1]),
  (u'Espaço em disco em Gigabytes', lambda row: row[2]),
  (u'Transferência mensal em Gigabits', lambda row: row[3]),
  (u'Preço', lambda row: row[4]),
  ]

details_fields = [
  (u'Domínio', lambda row: row[0]),
  (u'Memória RAM em Mb', lambda row: row[1]),
  (u'Espaço em disco em GB', lambda row: row[2]),
  (u'Transferência mensal em GB', lambda row: row[3]),
  (u'Distribuição', lambda row: row[4]),
  (u'Painel de controle', lambda row: row[5]),
  (u'Mensalidade', lambda row: row[6]),
  (u'Valor referente a este mês', lambda row: row[7]),
  ]

def dict_html_table(mydict):
  output = '<table>'
  for key, value in mydict.iteritems():
    line = '<tr><th>%s</th><td>%s</td></tr>' % (key, value)
    output = output + line
  output = output + '</table>'
  return output

class DNSRecordForm(FastDataGrid):
  add_link_title="Adiciona novo registro"
  show_add_link=False

  def get_edit_url(self, row=None):
    return lambda row: url(['/painel','dns',
    'dominio_editar_registro',
      str(row.id)])
  #def get_add_url(self):
  #  return lambda x=None: url(['/painel',
  #  'dominio_registro_adiciona', self.domain]) 
  def get_delete_url(self, row=None):
    return lambda row: url(['/painel','dns', 
    'dominio_apagar_registro', 
      str(row.id)])

  #get_edit_url = staticmethod(get_edit_url)
  #get_add_url = staticmethod(get_add_url)
  #get_delete_url = staticmethod(get_delete_url)

class UniqueDomain(validators.FancyValidator):
  "Validator to confirm a given domain name is unique."
  messages = {'notUnique': u'Este domínio já está sendo usado.'}

  def _to_python(self, value, state):
    if not server_domain_is_unique(value):
      raise validators.Invalid(self.message('notUnique', state), value, state)
    return value

class AdminMailFields(widgets.WidgetsList):
  sender=widgets.TextField("sender",default='suporte@yourbase.com.br')
  rcpts=widgets.TextArea("rcpts",
    label=u"Destinatarios separados por espacos")
  subject=widgets.TextField("subject")
  body=widgets.TextArea("body")

class AdminMailSchema(validators.Schema):
  sender= validators.NotEmpty()
  to= validators.NotEmpty()
  subject= validators.NotEmpty()
  body= validators.NotEmpty()

class ContactFields(widgets.WidgetsList):
  email = widgets.TextField("email", 
  label=u"Seu e-mail (será validado)")
  body = widgets.TextArea("body", label=u"Sua mensagem")    
  
class ContactSchema(validators.Schema):
  email = validators.Email()
  body = validators.NotEmpty()

class OrderFields(widgets.WidgetsList):
  plan = widgets.HiddenField("plan")
  domainname =  widgets.TextField("domainname", label=u"Domínio*",
    help_text=u"Este nome servirá para identificar seu VPS em\
    nosso painel de controle. Você não precisa tê-lo registrado\
    ainda. (ex: 'suaempresa.com.br)'")
  distro = widgets.RadioButtonList("distro", 
    label=u'Distribuição*', options=distro_options,default=1 )
#  disco = widgets.RadioButtonList("disco", 
#    label=u'Espaço em disco, em Gb*', options=disk_plans[1],default=1 )
  panel = widgets.RadioButtonList("panel",
    label=u"Painel de Controle*", options=panel_options,default=1
    )
  notes = widgets.TextArea("notes", label=u"Observações",
    help_text=u"Quer que instalemos algum software pra você? Pra\
    que finalidade utilizará seu servidor? Utilize esse campo \
    para fazer solicitações e comentários sobre este servidor.")

class OrderSchema(validators.Schema):
  plan = validators.NotEmpty()
  distro = validators.OneOf(distro_codes)
#  disco = validators.NotEmpty() 
  domainname = validators.All(UniqueDomain(), validators.NotEmpty())

class DNSDomainFields(widgets.WidgetsList):
  domain_name =  widgets.TextField("domain_name", label=u"Domínio")
  main_address = widgets.TextField("main_address", label=u"IP do\
  servidor principal", help_text=u"""Caso preencha este campo,
  utilizaremos esse endereço como valor inicial do registro MX e dos
  nomes '<seudominio>.com.br' e 'www.<seudominio>.com.br'.
  Provavelmente você deve inserir o IP do seu VPS aqui.""")

dns_record_types=[
  ('A', u"A - mapeamento de IPs"),
  ('MX', u"MX - servidores de e-mail"),
  ('NS', u"NS - servidores de nome"),
  ('SOA', u"SOA - configurações da zona"),
  ('CNAME', u"CNAME - Aliases"),
  ('TXT', u"TXT - Textos (incluindo SPF)"),
  ]

class DNSRecordFields(widgets.WidgetsList):
  name = widgets.TextField("name", label=u"Nome",
    help_text=u"Domínio ou sub-domínio ao qual este\
    registro se aplica.")
  type = widgets.SingleSelectField("type", label=u"Tipo",
    options=dns_record_types, default='A')
  content=widgets.TextField('content', label=u"Conteúdo",
    help_text=u"IP, nome de host, etc."
    )
  prio=widgets.TextField('prio', label=u"Prioridade",
    help_text=u"Valor inteiro",
    default='0')
  domain_id = widgets.HiddenField("domain_id")
  domain_name = widgets.HiddenField("domain_name")
  # record_id won't necessarily be validated
  # - for example, in a edit form
  record_id = widgets.HiddenField("record_id")

class DNSRecordSchema(validators.Schema):
  name = validators.All(validators.NotEmpty(),
    validators.String())
  type = validators.All(validators.NotEmpty(),
    validators.String())
  content = validators.All(validators.NotEmpty(),
    validators.String())
  prio = validators.All(validators.NotEmpty(),
    validators.Int())
  domain_id = validators.All(validators.NotEmpty(),
    validators.Int())
  domain_name = validators.All(validators.NotEmpty(),
    validators.String())

class EditDNSRecordSchema(validators.Schema):
  name = validators.All(validators.NotEmpty(),
    validators.String())
  type = validators.All(validators.NotEmpty(),
    validators.String())
  content = validators.All(validators.NotEmpty(),
    validators.String())
  prio = validators.All(validators.NotEmpty(),
    validators.Int())

class UniqueDNSDomain(validators.FancyValidator):
  "Validator to confirm a given domain name is unique."
  messages = {'notUnique': u'Este domínio já está cadastrado.'}

  def _to_python(self, value, state):
    if not dns_domain_is_unique(value):
      raise validators.Invalid(self.message('notUnique', state), value, state)
    return value

class DNSDomainSchema(validators.Schema):
  domain_name = validators.All(
     validators.NotEmpty(),
     UniqueDNSDomain(),
     validators.Regex(r"^[a-zA-Z.\-0-9]*$"))
  main_address = \
    validators.Regex(r'^(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b|)$')

dns_edit_form=DNSRecordForm(fields=[
  ('Tipo', 'type'),
  ('Nome','name'),
  ('Valor','content'),
  ('Prioridade', 'prio'),
  ('TTL', 'ttl'),
  ])

new_domain_form = widgets.TableForm(fields=DNSDomainFields(),
  validator=DNSDomainSchema(),
  submit_text=u'Envia', action="/painel/dns/dominio_insere")

edit_domain_record_form = widgets.TableForm(fields=DNSRecordFields(),
  validator=EditDNSRecordSchema(),
  submit_text=u'Envia',
  action="/painel/dns/dominio_atualiza_registro")

new_domain_record_form = widgets.TableForm(fields=DNSRecordFields(),
  validator=DNSRecordSchema(),
  submit_text=u'Envia', action="/painel/dns/dominio_registro_insere")

admindevedores_form = FastDataGrid(fields=[
  ('Pubid','pubid'),
  ('Description','description'),
  ('Server',lambda invoice: invoice.server.domain),
  ('User', lambda invoice: invoice.server.owner.email_address),
  ('Amount','amount_real'),
  ])
